package com.albon.baseball;

import java.util.ArrayList;
import java.util.HashMap;



import com.albon.alarm.BaseballSetAlarm;
import com.albon.alarm.StaticVariable;

import com.albon.sportsalarm.R;
import com.albon.util.Logg;
import com.albon.util.Schedule_Calendar;
import com.albon.util.Shared;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class BaseballLeague extends Activity implements OnClickListener, StaticVariable{
	private final String TAG = "Premier_League";
	
	
	private BaseballParser bParser;
	private ListView listView;
	private TextView titleText;
	private TextView monthText;
	private Button monthPrevious;
    private Button monthNext;
    
	private String league_title = "";
	private String league_name = "";
	private int world = 0;
	
	private String mYear; //올해
	private String mMonth; //이번달 
	private Schedule_Calendar sc;
	 
	private BaseballAdapter mBaseballAdapter;
	private ArrayList<HashMap<String, String>> data;
	private ArrayList<Baseball> baseballArrayList;
	
	private DatabaseHelper mDBHelper = null;
    private SQLiteDatabase db = null;
    
    private TextView mMoreText;
    private LinearLayout mMoreLayout;
    
	public Shared pref;
	
	private TextView mStatusTextView;
	private int itemNum;
	private int totalListNum;
	
    private void init(){
    	titleText = (TextView)findViewById(R.id.title);
    	titleText.setText(league_title);
    	monthText = (TextView)findViewById(R.id.monthText);
    	monthPrevious = (Button)findViewById(R.id.monthPrevious);
    	monthPrevious.setOnClickListener(this);
    	monthNext = (Button)findViewById(R.id.monthNext);
    	monthNext.setOnClickListener(this); 
    	
    	mStatusTextView = (TextView) findViewById(R.id.status);
//        mStatusTextView.setText("idle");
    }
    
	private final Handler handler = new Handler() {
		public void handleMessage(Message msg) {		
			
			 Logg.d(TAG, "data size : "+data.size());
			 baseballArrayList = new ArrayList<Baseball>();
			 totalListNum = data.size();
			 
			 if (totalListNum >= 20) {
				 for(itemNum=0; itemNum<20; itemNum++) {
					 if(data.get(itemNum).size()!=0) {
						 Baseball baseball = new Baseball(itemNum, league_title, data.get(itemNum).get("enable"), data.get(itemNum).get("real_date"), data.get(itemNum).get("real_time"), data.get(itemNum).get("compare_date"), data.get(itemNum).get("a_team"), data.get(itemNum).get("b_team"), data.get(itemNum).get("score"), data.get(itemNum).get("notification"), data.get(itemNum).get("stadium"), data.get(itemNum).get("reague"));
						 baseball.setBtnClicked(Boolean.valueOf(data.get(itemNum).get("enable")));
						 baseball.setmYear(mYear);
						 baseball.setmMonth(mMonth);
						 baseballArrayList.add(baseball);					
					 }				
				 }
			 } else {
				 for (itemNum=0; itemNum<totalListNum; itemNum++) {
					 if(data.get(itemNum).size()!=0) {
						 Baseball baseball = new Baseball(itemNum, league_title, data.get(itemNum).get("enable"), data.get(itemNum).get("real_date"), data.get(itemNum).get("real_time"), data.get(itemNum).get("compare_date"), data.get(itemNum).get("a_team"), data.get(itemNum).get("b_team"), data.get(itemNum).get("score"), data.get(itemNum).get("notification"), data.get(itemNum).get("stadium"), data.get(itemNum).get("reague"));
						 baseball.setBtnClicked(Boolean.valueOf(data.get(itemNum).get("enable")));
						 baseball.setmYear(mYear);
						 baseball.setmMonth(mMonth);
						 baseballArrayList.add(baseball);					
					 }
				 }
			 }
			
			 listViewUpdate();
		}
	};
	
	private void listViewUpdate() {
		
		mBaseballAdapter = new BaseballAdapter(this, R.layout.sports_item_row, baseballArrayList);
		Logg.d(TAG, "listViewUpdate");
		mMoreLayout = (LinearLayout) View.inflate(this, R.layout.more, null);
        mMoreLayout.setVisibility(View.INVISIBLE);
        listView.addFooterView(mMoreLayout);
		listView.setAdapter(mBaseballAdapter);
		
		listView.setOnScrollListener(new OnScrollListener() {
			
			// @Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			
			}
			
			// @Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
					if (totalListNum >= itemNum + 20) {
						int tmpEnd = itemNum + 20;
						
						for ( ; itemNum < tmpEnd; itemNum++) {
							if(data.get(itemNum).size()!=0) {
								 Baseball baseball = new Baseball(itemNum, league_title, data.get(itemNum).get("enable"), data.get(itemNum).get("real_date"), data.get(itemNum).get("real_time"), data.get(itemNum).get("compare_date"), data.get(itemNum).get("a_team"), data.get(itemNum).get("b_team"), data.get(itemNum).get("score"), data.get(itemNum).get("notification"), data.get(itemNum).get("stadium"), data.get(itemNum).get("reague"));
								 baseball.setBtnClicked(Boolean.valueOf(data.get(itemNum).get("enable")));
								 baseball.setmYear(mYear);
								 baseball.setmMonth(mMonth);
								 baseballArrayList.add(baseball);					
							 }	
						}
					} else {
						for ( ; itemNum < totalListNum; itemNum++) {
							if(data.get(itemNum).size()!=0) {
								 Baseball baseball = new Baseball(itemNum, league_title, data.get(itemNum).get("enable"), data.get(itemNum).get("real_date"), data.get(itemNum).get("real_time"), data.get(itemNum).get("compare_date"), data.get(itemNum).get("a_team"), data.get(itemNum).get("b_team"), data.get(itemNum).get("score"), data.get(itemNum).get("notification"), data.get(itemNum).get("stadium"), data.get(itemNum).get("reague"));
								 baseball.setBtnClicked(Boolean.valueOf(data.get(itemNum).get("enable")));
								 baseball.setmYear(mYear);
								 baseball.setmMonth(mMonth);
								 baseballArrayList.add(baseball);					
							 }	
						}
					}
					mBaseballAdapter.notifyDataSetChanged();
				}
			}
		});

		//listView.setOnTouchListener(mOnTouchListener);
		listView.setOnItemClickListener(alarmOnItemClickListener);
	}
	
	
	@SuppressLint("NewApi") @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		final Window win = getWindow();
        win.requestFeature(Window.FEATURE_NO_TITLE);
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON );
		setContentView(R.layout.soccer_league);
		league_title = getIntent().getStringExtra("league_title");
		league_name = getIntent().getStringExtra("league_name");
		world = getIntent().getIntExtra("world", 0); //해외인지 국내인지 판단 0은 해외 1은 국내
		/*****************************************
		 * 안드로이드 3.0 이상 부터 네트웍 통신시 android.os.NetworkOnMainThreadException 에러 발생
		 * onCreate메소드 안에 StrictMode를 추가
		 * 참고 http://android-developers.blogspot.kr/2010/12/new-gingerbread-api-strictmode.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+blogspot/hsDu+(Android+Developers+Blog) 
		 *****************************************/		
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads()          
		.detectDiskWrites()
		.detectNetwork()              
		.penaltyLog().build());   
		
		pref = new Shared(getBaseContext());
		
		 mDBHelper = new DatabaseHelper(this, DatabaseHelper.DATABASE_NAME);
	        if(db == null){        	
	        	db = mDBHelper.getWritableDatabase(); 
			}
	        
		data = new ArrayList<HashMap<String, String>>();
		
		
		listView = (ListView)findViewById(R.id.listView1);
		
		init();
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		sc = new Schedule_Calendar();
    	setMonthText();
	}		
	
	private void setMonthText() {
        mYear = sc.getCurYear();
        mMonth = sc.getCurMonth();
		 Logg.d(TAG, "mYear : "+mYear);
		 Logg.d(TAG, "mMonth : "+mMonth);
		 monthText.setText(mYear+"."+mMonth);
		 bParser = null;
		 bParser = new BaseballParser(BaseballLeague.this, handler, data, world, mYear, mMonth, league_name);
		 bParser.parser();		
    }
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
				
		switch (v.getId()) {
		case R.id.monthPrevious:
			sc.setPreviousMonth();
			setMonthText();
			break;
		case R.id.monthNext:
			sc.setNextMonth();
			setMonthText();
			break;

		}
		//sParse.parser();
	}
	
	//클릭이벤트
	AdapterView.OnItemClickListener alarmOnItemClickListener = new AdapterView.OnItemClickListener(){

		public void onItemClick(AdapterView parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			Baseball baseball = (Baseball) view.getTag();
			Log.d(TAG, "onClick id : "+id+", view id = "+baseball.getId());
			Log.d(TAG, "onClick id : "+id+", baseball.getScore() = "+baseball.getScore());
			if(baseball.getScore().equals("")){ // 스코어가 없는것만 알람 설정할수 있도록
				Intent set_alarm_intent = new Intent(BaseballLeague.this, BaseballSetAlarm.class);
				set_alarm_intent.putExtra("league_title", league_title);
				set_alarm_intent.putExtra("compare_date", baseball.getCompare_date());
				set_alarm_intent.putExtra("a_team", baseball.getA_team());
				set_alarm_intent.putExtra("b_team", baseball.getB_team());
				set_alarm_intent.putExtra("real_date", baseball.getReal_date());
				set_alarm_intent.putExtra("real_time", baseball.getReal_time());
				set_alarm_intent.putExtra("year", mYear);
				set_alarm_intent.putExtra("month", mMonth);
				set_alarm_intent.putExtra("stadium", baseball.getStadium());
				
				startActivity(set_alarm_intent);
			}else{
				Toast.makeText(BaseballLeague.this, R.string.past_game, Toast.LENGTH_SHORT).show();
			}
		}
		
	};
	
	private int getParserData(){		
		return pref.getInt(PARSERVALUE, 0);
	}
}
